package com.coocaa.app.gamecenter.pages.arsenal.view;

import android.content.Context;
import android.widget.ScrollView;
import android.widget.Scroller;

import com.coocaa.x.framework.utils.LogUtils;

import org.litepal.util.LogUtil;

/**
 * Created by xfk on 2015/11/8 0008.
 */
public class ArsenalScrollView extends ScrollView {
    private static String tag = "arsenal";
    private Context mContext;
    private int smoothY = 0;
    private int toSmoothYNum = 0;
    private boolean isInvokedListener = false;
    private OnScrollEndListener mOnScrollEndListener;
    private Scroller mScroller;
    public interface OnScrollEndListener {
        public void setScrollEnd(int y);
    }

    public ArsenalScrollView(Context context) {
        super(context);
        mContext = context;
        mScroller = new Scroller(mContext);
    }


    //调用此方法滚动到目标位置
    public void mySmoothScrollTo(int fx, int fy) {
        LogUtils.i("1116", "mySmoothScrollTo");
        int dx = fx - mScroller.getFinalX();
        int dy = fy - mScroller.getFinalY();
        mySmoothScrollBy(dx, dy);
    }

    //调用此方法设置滚动的相对偏移
    public void mySmoothScrollBy(int dx, int dy) {
        //设置mScroller的滚动偏移量
        mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy, 500);
        invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用，否则不一定会刷新界面，看不到滚动效果
    }

    @Override
    public void computeScroll() {

        //先判断mScroller滚动是否完成
        if (mScroller.computeScrollOffset()) {

            //这里调用View的scrollTo()完成实际的滚动
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //必须调用该方法，否则不一定能看到滚动效果
            postInvalidate();
        }

        super.computeScroll();
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 4);
    }

    @Override
    public void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
//        LogUtils.i(tag, "smoothY: "+smoothY+", y = "+y);
//        if(smoothY == y)
//            toSmoothYNum++;
        if ((y == smoothY || y == 0 || (this.getHeight() + y >= this.computeVerticalScrollRange()))
                && !isInvokedListener) {
            isInvokedListener = true;
            if (mOnScrollEndListener != null) {
                mOnScrollEndListener.setScrollEnd(y);
            }
        }
        this.getMeasuredWidth();
    }

    public void smoothScroll(int x, int y) {
        mySmoothScrollTo(x, y);
        smoothY = y;
        toSmoothYNum = 0;
        isInvokedListener = false;
        LogUtils.i(tag, "smoothY = "+smoothY+", VerticalScrollRange = "+this.computeVerticalScrollRange());
    }

    public void setmOnScrollEndListener(OnScrollEndListener onScrollEndListener){
        this.mOnScrollEndListener =onScrollEndListener;
    }
}
